import 'dart:convert';

import 'package:dio/dio.dart' as Resp;
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:ty_smart_watch/bean/more_weather_bean.dart';
import 'package:ty_smart_watch/bean/now_weather_bean.dart';
import 'package:ty_smart_watch/utils/weather_util.dart';

import '../../bean/geo_bean.dart';
import '../../common/global_data.dart';
import '../../utils/http_util.dart';
import 'controller/weather_controller.dart';

class GetGeoLocator {
  getLocation() async {
    bool serviceEnabled;
    LocationPermission permission;

    // 检查位置服务是否可用。
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      // 位置服务不可用，不再继续访问位置，也不会向 APP 的用户请求允许使用位置服务。
      // print('Location services are disabled.');
      return Future.error('Location services are disabled.');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        // 权限被拒绝，下次会继续尝试请求权限（安卓的shouldShowRequestPermissionRationale也会返回 true 。
        // 按照安卓的指南，这时APP 会显示一个有说明信息的界面。）
        // print('Location permissions are denied');
        return Future.error('Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      // 权限被永久拒绝，进行适当处理。
      // print('Location permissions are permanently denied, we cannot request permissions.');
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    //更新时间间隔过近，不处理。
    var currentTime = DateTime.now().millisecondsSinceEpoch;
    if (currentTime - GlobalData.updateGeoTime < 1 * 60 * 60 * 1000) {
      return;
    }

    // 至此说明已被授权，可以继续访问设备的位置了。
    var location = await Geolocator.getCurrentPosition(forceAndroidLocationManager: true);
    print("location :  $location");
    //更新缓存时间
    GlobalData.updateGeoTime = currentTime;

    //通过坐标获取Geo位置信息
    getGeoInfo(location.latitude, location.longitude);
    //通过坐标获取今日天气信息
    getTodayWeatherInfo(location.latitude, location.longitude);
    //通过坐标获取未来天气信息
    getFutureWeatherInfo(location.latitude, location.longitude);
  }

  ///获取位置信息
  getGeoInfo(lat, lng) async {
    print("lat  $lat , lng  $lng");

    final WeatherController weatherController = Get.find();
    var dio = HttpUtil.instance?.getDio();
    Resp.Response response = await dio.get(
        "https://geoapi.qweather.com/v2/city/lookup?location=$lng,$lat&key=715fe233158841dcbe10e4ba73ffe32f");
    try {
      Map<String, dynamic> geoMap = jsonDecode(response.toString());
      GeoBean geoBean = GeoBean.fromJson(geoMap);
      print("省： ${geoBean.location?[0].adm1} ; 市： ${geoBean.location?[0].adm2} ");
      weatherController.updateZone("${geoBean.location?[0].adm1} ${geoBean.location?[0].adm2}");

      WeatherUtil.updateGeo(geoBean);
      // WeatherUtil.sendTodayWeatherToWatch();
      // WeatherUtil.sendMoreWeatherToWatch();
    } catch (e) {
      print("e: $e");
    }
  }

  ///获取今日天气
  getTodayWeatherInfo(lat, lng) async {
    final WeatherController weatherController = Get.find();
    var dio = HttpUtil.instance?.getDio();
    Resp.Response response = await dio.get(
        "https://devapi.qweather.com/v7/weather/now?location=$lng,$lat&key=715fe233158841dcbe10e4ba73ffe32f");
    print("天气 ： $response");
    try {
      Map<String, dynamic> weatherMap = jsonDecode(response.toString());
      NowWeatherBean nowWeatherBean = NowWeatherBean.fromJson(weatherMap);
      print("天气： ${nowWeatherBean.now?.text} ; 温度： ${nowWeatherBean?.now?.temp} ");
      weatherController.updateMode(nowWeatherBean.now?.text ?? "未知");
      weatherController.updateTemperature(nowWeatherBean.now?.temp ?? "未知");

      WeatherUtil.updateNowWeather(nowWeatherBean);
      // WeatherUtil.sendTodayWeatherToWatch();
    } catch (e) {
      print("e: $e");
    }
  }

  ///获取未来天气
  getFutureWeatherInfo(lat, lng) async {
    final WeatherController weatherController = Get.find();
    var dio = HttpUtil.instance?.getDio();
    Resp.Response response = await dio.get(
        "https://devapi.qweather.com/v7/weather/7d?location=$lng,$lat&key=715fe233158841dcbe10e4ba73ffe32f");
    print("未来天气 ： $response");
    try {
      Map<String, dynamic> weatherMap = jsonDecode(response.toString());
      MoreWeatherBean moreWeatherBean = MoreWeatherBean.fromJson(weatherMap);

      WeatherUtil.updateMoreWeather(moreWeatherBean);
      // WeatherUtil.sendTodayWeatherToWatch();
      // WeatherUtil.sendMoreWeatherToWatch();
    } catch (e) {
      print("e: $e");
    }
  }
}
